package com.to8to.kitt.client;

import java.util.HashSet;
import java.util.Set;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.to8to.kitt.esb.ZK;
import com.to8to.kitt.utils.NettyUtils;

public class ThriftClientMonitor {
	
	public static Logger logger = LoggerFactory.getLogger(ThriftClientMonitor.class);
	
	public static Set<ThriftClientInvocationHandler> handlers = new HashSet<ThriftClientInvocationHandler>();
	
	public static PathChildrenCache childcache;
	
	public static void start(String path) {
		
		logger.info("监听总线服务: " + path);
		
		childcache = new PathChildrenCache(ZK.ZK_CLIENT, path, true);
		
		try {
			
			childcache.start();

			childcache.getListenable().addListener(new PathChildrenCacheListener() {

				@Override
				public void childEvent(CuratorFramework client,
						PathChildrenCacheEvent event) throws Exception {
					if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) {
						for (ThriftClientInvocationHandler handler : handlers)
							handler.resetThreadLocalClients();
					}
					else if (event.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED) {

					}
				}
			});

		} catch (Throwable e) {
			NettyUtils.exitIfOutOfMemory(e);
			e.printStackTrace();
		}
	}
}
